package com.jarasoft.AMP3MP;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class AndroidMP3MusicPlayerActivity extends Activity {

	private Activity main_activity;
	private Button buttonprev, buttonplaypause, buttonstop, buttonnext;
	private Button buttonarti, buttondisc, buttonfolder;
	private ProgressBar progressbar;
	private TextView songinfo;
	private BroadcastReceiver playpausereceiver, playbreceiver, pausebreceiver, progressreceiver, songinforeceiver;
	private static boolean isRunning = false;
	private List<List<String>> indextracks;
	private ListView songlist;
	private String curlist;
	private SharedPreferences pref;
	private Editor prefedit;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.player);
		
		pref = getSharedPreferences("controlmp3", MODE_WORLD_WRITEABLE);
      prefedit = pref.edit();
      curlist = pref.getString("LIST", MediaStore.Audio.Media.ARTIST);
      System.out.println(pref.getString("LIST", MediaStore.Audio.Media.ARTIST));

		main_activity = this;
		isRunning = true;
		startbroad();

		buttonprev = (Button) findViewById(R.id.bprev);
		buttonprev.setOnClickListener(prevbutListener);

		buttonplaypause = (Button) findViewById(R.id.bplay);
		buttonplaypause.setOnClickListener(playpausebutListener);

		buttonstop = (Button) findViewById(R.id.bstop);
		buttonstop.setOnClickListener(stopbutListener);

		buttonnext = (Button) findViewById(R.id.bnext);
		buttonnext.setOnClickListener(nextbutListener);

		progressbar = (ProgressBar) findViewById(R.id.progressBar);
		progressbar.setMax(1);
		progressbar.setProgress(0);

		songinfo = (TextView) findViewById(R.id.songinfo);
		songinfo.setSelected(true);

		buttonarti = (Button) findViewById(R.id.barti);
		buttonarti.setOnClickListener(artibutListener);

		buttondisc = (Button) findViewById(R.id.bdisc);
		buttondisc.setOnClickListener(discbutListener);

		buttonfolder = (Button) findViewById(R.id.bfolder);
		buttonfolder.setOnClickListener(folderbutListener);

		indextracks = new ArrayList<List<String>>();
		songsby(curlist);

		if (AndroidMP3MusicPlayerService.isPause() || !AndroidMP3MusicPlayerService.isRunning()) {
			buttonplaypause.setBackgroundResource(R.drawable.b_play);
		} else {
			buttonplaypause.setBackgroundResource(R.drawable.b_pause);
		}    

		songlist = (ListView) findViewById(R.id.listView1);
		songlist.setAdapter(new MultiAdapter(this));
		songlist.setOnItemClickListener(new OnItemClick());

	}

	@Override
	public void onDestroy() {
		stopbroad();
		isRunning = false;
		super.onDestroy();
	}

	private OnClickListener prevbutListener = new OnClickListener() {
		public void onClick(View v) {
			main_activity.sendBroadcast(new Intent(AndroidMP3MusicPlayerService.PREVACTION));
		}
	};

	private OnClickListener playpausebutListener = new OnClickListener() {
		public void onClick(View v) {
			main_activity.sendBroadcast(new Intent(AndroidMP3MusicPlayerService.PLAYPAUSEACTION));

		}
	};

	private OnClickListener stopbutListener = new OnClickListener() {
		public void onClick(View v) {
			main_activity.sendBroadcast(new Intent(AndroidMP3MusicPlayerService.STOPACTION));
		}
	};

	private OnClickListener nextbutListener = new OnClickListener() {
		public void onClick(View v) {
			main_activity.sendBroadcast(new Intent(AndroidMP3MusicPlayerService.NEXTACTION));
		}
	};

	private OnClickListener artibutListener = new OnClickListener() {
		public void onClick(View v) {
			songsby(MediaStore.Audio.Media.ARTIST);
			songlist.setAdapter(new MultiAdapter(main_activity));
			main_activity.sendBroadcast(new Intent(AndroidMP3MusicPlayerService.ARTISTACTION));
			curlist = MediaStore.Audio.Media.ARTIST;
	      prefedit.putString("LIST", MediaStore.Audio.Media.ARTIST);
	      prefedit.commit();
	      
	      System.out.println(pref.getString("LIST", MediaStore.Audio.Media.ARTIST));
		}
	};

	private OnClickListener discbutListener = new OnClickListener() {
		public void onClick(View v) {
			songsby(MediaStore.Audio.Media.ALBUM);
			songlist.setAdapter(new MultiAdapter(main_activity));
			main_activity.sendBroadcast(new Intent(AndroidMP3MusicPlayerService.DISCACTION));
			curlist = MediaStore.Audio.Media.ALBUM;
	      prefedit.putString("LIST", MediaStore.Audio.Media.ALBUM);
	      prefedit.commit();
	      
	      System.out.println(pref.getString("LIST", MediaStore.Audio.Media.ARTIST));
		}
	};

	private OnClickListener folderbutListener = new OnClickListener() {
		public void onClick(View v) {
			songsby(MediaStore.Audio.Media.DATA);
			songlist.setAdapter(new MultiAdapter(main_activity));
			main_activity.sendBroadcast(new Intent(AndroidMP3MusicPlayerService.FOLACTION));
			curlist = MediaStore.Audio.Media.DATA;
	      prefedit.putString("LIST", MediaStore.Audio.Media.DATA);
	      prefedit.commit();
	      
	      System.out.println(pref.getString("LIST", MediaStore.Audio.Media.ARTIST));
		}
	};

	private class OnItemClick implements OnItemClickListener {
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			Intent i = new Intent(AndroidMP3MusicPlayerService.PLAYPAUSEACTION);
			i.putExtra("POS", position);
			main_activity.sendBroadcast(i);
			view.setSelected(true);
		}
	}

	private void startbroad() {
		IntentFilter theFilter = new IntentFilter();
		theFilter.addAction(AndroidMP3MusicPlayerService.PLAYPAUSEACTION);
		playpausereceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				if (!AndroidMP3MusicPlayerService.isRunning()) {
					Intent i = new Intent(main_activity, AndroidMP3MusicPlayerService.class);
					i.putExtra("CURLIST", curlist);
					if (intent.hasExtra("POS")) {
						i.putExtra("POS", intent.getExtras().getInt("POS"));
					}
					main_activity.startService(i);
				}
			}
		};
		registerReceiver(playpausereceiver, theFilter);

		theFilter = new IntentFilter();
		theFilter.addAction(AndroidMP3MusicPlayerService.PLAYBACTION);
		playbreceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				buttonplaypause.setBackgroundResource(R.drawable.b_play);
			}
		};
		registerReceiver(playbreceiver, theFilter);

		theFilter = new IntentFilter();
		theFilter.addAction(AndroidMP3MusicPlayerService.PAUSEBACTION);
		pausebreceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				buttonplaypause.setBackgroundResource(R.drawable.b_pause);
			}
		};
		registerReceiver(pausebreceiver, theFilter);

		theFilter = new IntentFilter();
		theFilter.addAction(AndroidMP3MusicPlayerService.PROGRESSACTION);
		progressreceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				progressbar.setMax(intent.getExtras().getInt("MAXPB"));
				progressbar.setProgress(intent.getExtras().getInt("PROPB"));
			}
		};
		registerReceiver(progressreceiver, theFilter);

		theFilter = new IntentFilter();
		theFilter.addAction(AndroidMP3MusicPlayerService.SONGINFOACTION);
		songinforeceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				songinfo.setText(intent.getExtras().getString("SONGINFO"));
				int pos = intent.getExtras().getInt("POS");
				if (songlist.getSelectedItemPosition() != pos) {
					songlist.requestFocusFromTouch();
					songlist.setSelection(pos);
				}
			}
		};
		registerReceiver(songinforeceiver, theFilter);

	}

	private void stopbroad() {
		unregisterReceiver(playpausereceiver);
		unregisterReceiver(playbreceiver);
		unregisterReceiver(pausebreceiver);
		unregisterReceiver(progressreceiver);
		unregisterReceiver(songinforeceiver);
	}

	public static boolean isRunning() {
		return isRunning;
	}

	class MultiAdapter extends ArrayAdapter<List<String>> {

		public MultiAdapter(Context context) {
			super(context, R.layout.songlist, indextracks);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row;
			if (convertView == null) {
				LayoutInflater inflater = getLayoutInflater();
				row = inflater.inflate(R.layout.songlist, parent, false);
			} else
				row = convertView;
			TextView cate = (TextView) row.findViewById(R.id.Cate);
			TextView title = (TextView) row.findViewById(R.id.Title);

			row.setBackgroundResource(R.drawable.listcolor);

			if (position == 0) {
				cate.setVisibility(View.VISIBLE);

				cate.setText(indextracks.get(position).get(0));
			} else {
				if (!indextracks.get(position).get(0).equals(indextracks.get(position - 1).get(0))) {
					cate.setVisibility(View.VISIBLE);
					cate.setText(indextracks.get(position).get(0));
				} else {
					cate.setVisibility(View.GONE);
				}
			}

			title.setText(indextracks.get(position).get(1));

			return row;

		}

	}

	private void songsby(String orderby) {
		String[] projection = { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.TRACK,
		      MediaStore.Audio.Media.YEAR, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ALBUM_ID,
		      MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ALBUM_KEY, MediaStore.Audio.Media.TITLE,
		      MediaStore.Audio.Media.TITLE_KEY, MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.ARTIST };

		Cursor mCursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, null, null,
		      orderby);

		indextracks.clear();
		List<String> track;
		File song;
		String name;
		if (mCursor.moveToFirst()) {
			do {
				name = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
				if (name.endsWith(".mp3")) {
					track = new ArrayList<String>();
					song = new File(name);

					if (orderby.equals(MediaStore.Audio.Media.DATA)) {
						track.add(0, song.getParent());
					} else {
						track.add(0, mCursor.getString(mCursor.getColumnIndexOrThrow(orderby)));
					}
					track.add(1, song.getName());
					indextracks.add(track);
				}
			} while (mCursor.moveToNext());

		}

	}

}
